package com.ruoyi.stock2.config;

import com.sun.mail.util.MailSSLSocketFactory;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;

public class MailUtil implements Runnable {
    /**
     * When an object implementing interface <code>Runnable</code> is used
     * to create a thread, starting the thread causes the object's
     * <code>run</code> method to be called in that separately executing
     * thread.
     * <p>
     * The general contract of the method <code>run</code> is that it may
     * take any action whatsoever.
     *
     * @see Thread#run()
     */
    private String domain;// 发件人域名服务器
    private String email;// 收件人邮箱
    private String code;// 激活码
    private String bussi;
    public MailUtil(String email, String code, String domain, String bussi) {
        this.email = email;
        this.code = code;
        this.domain = domain;
        this.bussi = bussi;
    }
    public MailUtil() {

    }
    @Override
    public void run() {
        switch (bussi)
        {
            case "active"://帐号激活

                break;
            case "forget"://忘记密码

                break;
            default:
                test();
        }
    }

    public void test(){
// 1.创建连接对象javax.mail.Session
        // 2.创建邮件对象 javax.mail.Message
        // 3.发送一封激活邮件
        String from = "359642959@qq.com";// 发件人电子邮箱
        String host = "smtp.qq.com"; // 指定发送邮件的主机smtp.qq.com(QQ)|smtp.163.com(网易)

        Properties properties = System.getProperties();// 获取系统属性

        properties.setProperty("mail.smtp.host", host);// 设置邮件服务器
        properties.setProperty("mail.smtp.auth", "true");// 打开认证

        try {
            //QQ邮箱需要下面这段代码，163邮箱不需要
            MailSSLSocketFactory sf = new MailSSLSocketFactory();
            sf.setTrustAllHosts(true);
            properties.put("mail.smtp.ssl.enable", "true");
            properties.put("mail.smtp.ssl.socketFactory", sf);


            // 1.获取默认session对象
            Session session = Session.getDefaultInstance(properties, new Authenticator() {
                public PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication("359642959@qq.com", "zacmsfziegiebjei"); // 发件人邮箱账号、授权码
                }
            });


            // 2.创建邮件对象
            Message message = new MimeMessage(session);
            // 2.1设置发件人
            message.setFrom(new InternetAddress(from));
            // 2.2设置接收人
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(email));
            // 2.3设置邮件主题
            message.setSubject(code);

            // 2.4设置邮件内容
            String content = code;

            message.setContent(content, "text/html;charset=UTF-8");
            // 3.发送邮件
            Transport.send(message);

            System.out.println("邮件成功发送!");


            boolean flag = true;
            while (flag){
                Thread.sleep(1000);
                boolean k = pop3receive();
                if(k){
                    break;
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static boolean pop3receive() throws Exception {
        // 定义连接POP3服务器的属性信息
        String pop3Server = "pop.qq.com";
        String protocol = "imap";
        String username = "359642959@qq.com";
        String password = "zacmsfziegiebjei"; // QQ邮箱的SMTP的授权码，什么是授权码，它又是如何设置？

        Properties props = new Properties();
        props.setProperty("mail.transport.protocol", protocol); // 使用的协议（JavaMail规范要求）
        props.setProperty("mail.imap.host", pop3Server); // 发件人的邮箱的 SMTP服务器地址

        // 获取连接
        Session session = Session.getDefaultInstance(props);
        session.setDebug(false);

        // 获取Store对象
        Store store = session.getStore(protocol);
        store.connect(pop3Server, username, password); // POP3服务器的登陆认证

        // 通过POP3协议获得Store对象调用这个方法时，邮件夹名称只能指定为"INBOX"
        Folder folder = store.getFolder("INBOX");// 获得用户的邮件帐户
        folder.open(Folder.READ_WRITE); // 设置对邮件帐户的访问权限

        Message[] messages = folder.getMessages(folder.getMessageCount()-folder.getUnreadMessageCount()+1,folder.getMessageCount());// 得到邮箱帐户中的所有邮件

        for (Message message : messages) {
            String subject = "";
            try {
                subject = message.getSubject();// 获得邮件主题
                Address from = (Address) message.getFrom()[0];// 获得发送者地址
                Flags flags = message.getFlags();
                if (flags.contains(Flags.Flag.SEEN))
                    System.out.println("这是一封已读邮件");
                else {
                    System.out.println("未读邮件");
                }
                System.out.println("邮件的主题为: " + subject + "\t发件人地址为: " + from);
                System.out.println("邮件的内容为：");
                message.writeTo(System.out);// 输出邮件内容到控制台
            }catch (MessageRemovedException exception){
                exception.printStackTrace();
            }
        }

        folder.close(true);// 关闭邮件夹对象
        store.close(); // 关闭连接对象
        if(messages.length>0){
            return true;
        }
        return  false;
    }

    public static void main(String[] args) {

        //String randomCode = RandomStringUtils.randomNumeric(6) + UUID.randomUUID().toString().replaceAll("-","");
        //System.out.println(randomCode);
        MailUtil mailUtil = new MailUtil("359642959@qq.com","获取D盘文件目录", "wwww.baidu.com", "test");
        new Thread(mailUtil).start();
    }

    /*
    if("获取D盘文件目录".equals(subject)){
                    try {
                        List<String> list = OtherUtils.exec("cmd /c dir d:");
                        for (String str : list){
                            System.out.println(str);
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
     */
}
